package com.devin.avatar.module.system.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.devin.avatar.common.controller.BaseController;
import com.devin.avatar.common.entity.RequestParams;
import com.devin.avatar.module.system.entity.SysUser;
import com.devin.avatar.module.system.service.SysUserService;
import com.github.pagehelper.PageInfo;

@RequestMapping("/system/user")
@Controller
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    
    /**
	 * 显示列表页
	 * */
    @RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/system/userList";
	}
    
    /**
	 * 获取分页列表数据（JSON）
	 */
    @ResponseBody
    @RequestMapping({ "listData" })
    public PageInfo<SysUser> listData(SysUser sysUser, HttpServletRequest req, HttpServletResponse res) {
	RequestParams p = new RequestParams(req, res);
	sysUser.setRequstParams(p);
	return sysUserService.findPageInfo(sysUser, p.getPageNum(), p.getPageSize());
    }
    
    /**
	 * 显示新建或修改表单
	 */
    @RequestMapping(value = "form")
	public String form(SysUser sysUser, Model model) {
		model.addAttribute("sysUser", sysUser);
		return "modules/system/userForm";
	}
    
    /**
	 * 保存表单
	 */
	@RequestMapping(value = "save")
	public String save(SysUser sysUser, Model model, RedirectAttributes redirectAttributes) {
//		if (!beanValidator(model, sysUser)){
//			return form(sysUser, model);
//		}
	    sysUserService.save(sysUser);
		addMessage(redirectAttributes, "保存用户'" + sysUser.getName() + "'成功");
		return "redirect:/system/user/?repage";
	}
	
	/**
	 * 删除方法
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(SysUser sysUser, RedirectAttributes redirectAttributes) {
	    sysUserService.delete(sysUser);
		addMessage(redirectAttributes, "删除用户成功");
		return "redirect:/system/user/?repage";
	}
    

    @ResponseBody
    @RequestMapping({ "/get"})
    public SysUser get(@RequestParam(required = false) String id) {
	if (StringUtils.isNotBlank(id)) {
	    return sysUserService.get(id);
	} else {
	    return new SysUser();
	}
    }
}
